package cn.easyplatform.studio.cmd.identity;

import cn.easyplatform.studio.StudioException;
import cn.easyplatform.studio.dao.IdentityDao;
import cn.easyplatform.studio.interceptor.Command;
import cn.easyplatform.studio.interceptor.CommandContext;
import cn.easyplatform.studio.utils.GlobalVariableService;
import cn.easyplatform.studio.vos.LoginUserVo;
import cn.easyplatform.studio.vos.SMSVo;
import org.zkoss.util.resource.Labels;

import java.util.Date;
import java.util.List;

public class GetStudioRetrieveSMSCmd implements Command<Boolean> {
    private String userId;
    private String code;

    public GetStudioRetrieveSMSCmd(String userId, String code) {

        this.userId = userId;
        this.code = code;
    }

    @Override
    public Boolean execute(CommandContext cc) {
        IdentityDao dao = cc.getIdentityDao();
        LoginUserVo user = dao.getUser(userId);
        if (user == null)
            throw new StudioException(Labels.getLabel("forget.mobile.no.exist"));
        //获取手机号获取验证码信息
        List<SMSVo> smsVoList = GlobalVariableService.getOneInstance().getSmsVos();
        long diff = 600000;
        SMSVo currentSMSVo = null;
        for (SMSVo smsVo : smsVoList) {
            if (userId.equals(smsVo.getPhoneNO()) && SMSVo.SMSType.SMSRetrieve.getName().equals(smsVo.getType())) {
                currentSMSVo = smsVo;
                diff = new Date().getTime() -  currentSMSVo.getCreateDate().getTime();
            }
        }
        if (currentSMSVo == null || diff > 600000)
            throw new StudioException(Labels.getLabel("sms.set.error"));
        if (code.equals(currentSMSVo.getContent()) == false)
            throw new StudioException(Labels.getLabel("sms.input.error"));
        return true;
    }
}
